package com.xiaoai.httpClientTestService.httpclient.myown;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Old_http {
    public static void main(String[] args) throws IOException {

        // 1-构造一个url
        URL url = new URL("http://www.baidu.com");
//        URL url = new URL("http://localhost:8080/hello");

        // 2-构造一个连接 设置相关配置属性
        HttpURLConnection urlconn = (HttpURLConnection) url.openConnection();
        urlconn.setRequestMethod("GET"); //设置请求方式
        urlconn.setConnectTimeout(5000);
        urlconn.setReadTimeout(5000);
        urlconn.setUseCaches(false);

        // 3-设置请求头(请求属性) 这里为模拟浏览器
//        urlconn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36");

        // 4-获取连接
        urlconn.connect();

        // 5-获取连接的流对象 读取源码数据
        InputStream inputStream = urlconn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
        BufferedReader buff = new BufferedReader(inputStreamReader);

        String line = null;
        while ((line = buff.readLine()) != null){
            System.out.println(line);
        }
        inputStream.close();
        inputStreamReader.close();
        buff.close();
    }


}
